<template>
  <!-- 费用（条码申请项目） -->
  <div id="BacObserSelection">
    <vxe-modal v-model="modalShow" id="specAdditionModal" width="85vw" height="80vh" show-zoom show-footer
      @hide="closeModal">
      <template #title>
        <span>选择菌落观察结果</span>
      </template>
      <template #default>
        <Splitpanes horizontal>
          <Pane :size="10" v-if="isShowCulMediumBox">
            <div>培养基</div>
            <div>
              <!-- <el-checkbox-group v-model="formData.cultureMediums">
                <el-checkbox v-for="(item, index) in checkList" :label="item.name" :key="index">
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group> -->
              <el-radio-group v-model="formData.cultureMediums">
                <el-radio v-for="(item, index) in checkList" :label="item.name" :key="index">
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </div>
          </Pane>
          <Pane :size="90">
            <Splitpanes>
              <Pane :size="35">
                <vxe-toolbar class="bg-gray">
                  <template #buttons>
                    <vxe-input type="search" v-model="form.searchValue" clearable class="vxeInputSearch"
                      @search-click="findColonialMorphologyList" @clear="findColonialMorphologyList"
                      @keyup.enter.native="findColonialMorphologyList" placeholder="关键字查询"></vxe-input>
                  </template>
                </vxe-toolbar>
                <div :style="{ height: 'calc(100% - 40px)' }">
                  <vxe-table ref="colonialMorphologyTableRef" v-loading="additionLoading"
                    @current-change="colonialMorphologyRowClick" border height="auto" :data="specAdditionList"
                    class="mytable-scrollbar" :merge-footer-items="[{ row: 0, col: 0, rowspan: 1, colspan: 4 }]"
                    :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                      isArrow: true,
                      isTab: true,
                      isEdit: true
                    }" resizable show-overflow>
                    <vxe-column type="seq" title="#" width="30" align="left"></vxe-column>
                    <vxe-column field="name" title="形态名称" min-width="180"></vxe-column>
                    <vxe-column field="inputCode" title="输入码" width="80"></vxe-column>
                    <vxe-column field="description" title="描述" width="120"></vxe-column>
                    <vxe-column field="clinicalSignificanceh" title="临床意义" width="120"></vxe-column>
                    <vxe-column field="displayOrder" title="顺序" width="60"></vxe-column>
                  </vxe-table>
                </div>
              </Pane>
              <Pane :size="65">
                <div style="height: calc(100%)">
                  <el-scrollbar style="height: 100%">
                    <el-descriptions :column="1" class="CMTypeBox" border
                      v-for="(item, index) in colonialMorphologyTypeList" :key="index">
                      <el-descriptions-item label-class-name="CMTypeBox-title">
                        <template #label>
                          <div class="text-bold text-lg">{{ item.name }}</div>
                          <div>
                            <vxe-button type="text" class-name="vxe-icon-delete-fill text-red" content="清除选中"
                              @click="clearOptionChecked(item.code)"></vxe-button>
                          </div>
                        </template>
                        <el-row :gutter="10">
                          <el-col :span="3" v-for="(op, idx) in item.colonialMorphologyTypeOptList" :key="idx"
                            class="text item" @click.capture="radioChange(item.code, op.id)">
                            <el-card shadow="never">
                              <el-image style="width: 100%; height: 50px" :src="byteArrayToImage(op.imageBlob)"
                                fit="cover">
                                <!-- picUrlBase + op.imageUrl -->
                                <template #error>
                                  <div class="image-slot">
                                    <el-icon>
                                      <icon-picture />
                                    </el-icon>
                                  </div>
                                </template>
                              </el-image>
                            </el-card>
                            <div>
                              <el-checkbox v-model="op.isSelected" @change="radioChange(item.code, op.id)">
                                {{ op ? op.name : '' }}
                              </el-checkbox>
                            </div>
                          </el-col>
                        </el-row>
                      </el-descriptions-item>
                    </el-descriptions>
                  </el-scrollbar>
                </div>
              </Pane>
            </Splitpanes>
          </Pane>
        </Splitpanes>
      </template>
      <template #footer>
        <div class="flex justify-end">
          <vxe-button type="text" class="button-blue margin-left-xs" content="取消" @click="modalShow = false"></vxe-button>
          <vxe-button type="text" class="button-blue margin-left-xs" content="确定" @click="confirmClick"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import 'vxe-table/lib/style.css';
import { Splitpanes, Pane } from 'splitpanes';
import { Picture as IconPicture } from '@element-plus/icons-vue';

let { proxy }: any = getCurrentInstance();

let colonialMorphologyTableRef: any = ref(null);
let reqNo = ref(''); //接收传过来的检验结果id
let tableList = reactive([]);
let specAdditionList = reactive([]);
let checkList = reactive([]);

let props = defineProps({
  isShowCulMediumBox: { type: Boolean, default: true },/*是否显示培养基列表*/
});

// 表单绑定的数据
let formData = reactive({
  cultureMediums: ''
});
let loading = ref(false);
let additionLoading = ref(false);
let modalShow = ref(false);
let specAdditionForm = reactive({
  reqNo: '' //条码号)
}); //附加条码
let colonialMorphologyTypeList = reactive([]);
let currentRowIndex = ref(0); //索引
let currentColonialMorphology = reactive({});
let picUrlBase = (window as any).apiUrl.VITE_SERVER_URL;
let form = reactive({
  searchValue: '',
  colonialMorphologyId: ''
});
// 页面加载时更新报告单元/字典
onMounted(async () => {
  getDictItemsList(); //批量获取字典
});
defineExpose({
  showModal
});

// 获取培养基
async function getDictItemsList() {
  checkList.length = 0; //放入数据前清空数据
  const url = '/api/bac/bac-culture-medium/findBacCultureMediums';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then(async (res: any) => {
      checkList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取培养基数据异常', VxeNotifyType.error);
    });
};

//弹窗显示
function showModal(val1: any) {
  modalShow.value = true;
  formData.cultureMediums = '';
  getColonialMorphologyTypeList();
}

// 行点击事件
function colonialMorphologyRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    return;
  }
  currentRowIndex = rowIndex;
  currentColonialMorphology = row;
  const xTable = proxy.$refs.colonialMorphologyTableRef;
  xTable.setCurrentRow(row);
  colonialMorphologyIdChange(row.id);
}

function colonialMorphologyIdChange(id) {
  form.colonialMorphologyId = id;
  //清空选中的数据
  colonialMorphologyTypeList.forEach((key) => {
    if (key.colonialMorphologyTypeOptList) {
      key.colonialMorphologyTypeOptList.forEach((item) => {
        item.isSelected = false;
      });
    }
  });
  if (id) {
    findColonialMorphologyDetailLsit(id);
  }
}

// 获取菌落形态类型
function getColonialMorphologyTypeList() {
  colonialMorphologyTypeList.length = 0;
  loading.value = true;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'gremMorphologyType' } })
    .then((res: any) => {
      Object.assign(colonialMorphologyTypeList, res.data);
      res.data.forEach((item, index) => {
        getColonialMorphologyTypeOptList(item, index);
      });
      loading.value = false;
      findColonialMorphologyList();
    })
    .catch((err) => { });
}

function getColonialMorphologyTypeOptList(value, index) {
  const url = '/bac/germ/morphologyType/findListByType';
  const data = {
    morphologyType: value.code
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      res.data.forEach((item) => {
        item['isSelected'] = false;
      });
      value.radio = null;
      value.colonialMorphologyTypeOptList = res.data;
      colonialMorphologyTypeList[index] = Object.assign({}, value);
      proxy.$forceUpdate();
    })
    .catch((err) => {
      proxy.$alert(err.data.error.message, '提示');
    });
}
//获取列表
function findColonialMorphologyList() {
  specAdditionList.length = 0;
  loading.value = true;
  const url = '/bac/germ/morphology/findPageList';
  const data = {
    searchValue: IsEmpty(form.searchValue) ? '' : form.searchValue.trim()
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      specAdditionList.push(...res.data);
      proxy.$nextTick(() => {
        colonialMorphologyRowClick({ row: specAdditionList[0], rowIndex: 0 });
      });
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage('获取列表', VxeNotifyType.error);
    });
}

// 获取菌落形态明细
function findColonialMorphologyDetailLsit(id) {
  loading.value = true;
  const url = '/bac/germ/morphology/findListByMorphologyId';
  const data = {
    id: id
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      res.data.forEach((item, index) => {
        //设置为true
        colonialMorphologyTypeList.forEach((e) => {
          e.colonialMorphologyTypeOptList.forEach((op) => {
            if (op.id === item.id) {
              op.isSelected = true;
            }
          });
        });
      });
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage('获取明细', VxeNotifyType.error);
    });
}

// 关闭弹框
function closeModal() {
  modalShow.value = false;
  specAdditionForm.reqNo = '';
  formData.cultureMediums = "";
}

function clearOptionChecked(code) {
  colonialMorphologyTypeList.forEach((e) => {
    if (e.code === code) {
      e.colonialMorphologyTypeOptList.forEach((op) => {
        op.isSelected = false;
      });
    }
  });
}
function radioChange(code, resultId) {
  colonialMorphologyTypeList.forEach((e) => {
    e.colonialMorphologyTypeOptList.forEach((op) => {
      if (e.code === code && op.id === resultId && op.isSelected) {
        op.isSelected = true;
      } else if (e.code === code && op.id !== resultId) {
        op.isSelected = false;
      }
    });
  });
}

/**确定形态选择 */
function confirmClick() {
  let morphology = '';
  colonialMorphologyTypeList.forEach((key) => {
    if (key.colonialMorphologyTypeOptList) {
      key.colonialMorphologyTypeOptList.forEach((item) => {
        if (item.isSelected) {
          morphology = morphology + item.name + ',';
        }
      });
    }
  });
  /*  if (IsEmpty(morphology)) {
      VxeMessage('请选择观察形态', VxeNotifyType.error);
      return;
    }*/
/*  if (formData.cultureMediums.length === 0 && props.isShowCulMediumBox) {
    VxeMessage('请选择培养基', VxeNotifyType.error);
    return;
  }*/
  let data = {
    cultureMedium: '',
    morphology: '',
    description: ''
  };
  // data.cultureMedium = formData.cultureMediums.join(',');
  data.cultureMedium = formData.cultureMediums;
  data.description = currentColonialMorphology.description;
  data.morphology = morphology.substring(0, morphology.length - 1);
  proxy.$emit('obserConfirm', data);
  modalShow.value = false;
}
/**确定形态选择 */
function confirmClickV1() {
  let morphology = '';
  const selRow = colonialMorphologyTableRef.value?.getCurrentRecord();
  if (!selRow) {
    VxeMessage('请选择菌落形态', VxeNotifyType.error);
    return;
  }
  let data = {
    cultureMedium: '',
    morphology: ''
  };
  data.cultureMedium = formData.cultureMediums;
  data.morphology = selRow.description;
  proxy.$emit('obserConfirm', data);
  modalShow.value = false;
}
/* byte[] 转涂片 */
function byteArrayToImage(byteArray) {
  return `data:image/jpeg;base64,${byteArray}`;
}
</script>
<style lang="scss" scoped>
#BacObserSelection {
  height: 100%;

  :deep(.vxe-modal--content) {
    padding: 0;
  }

  :deep(.CMTypeBox) {
    margin-bottom: 5px;

    .el-col>div:last-child {
      text-align: center;

      .el-radio {
        margin-top: 4px;

        .el-radio__label {
          font-size: 12px;
        }
      }
    }
  }

  :deep(.CMTypeBox-title) {
    color: #333;
    font-size: 14px;
    width: 70px;
  }
}

:deep(.el-card__body) {
  padding: 2px !important;
}</style>
